package sapling.web.admin;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sapling.dao.LandMassDao;
import sapling.dao.OutboundOrderDao;
import sapling.dao.TreeDao;
import sapling.model.LandMass;
import sapling.model.OutboundOrder;
import sapling.model.Tree;
import sapling.model.TreeWell;
import sapling.service.CostService;
import sapling.service.PushService;
import sapling.service.StorageService;
import sapling.service.TreeService;
import sapling.utils.FileUtil;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.util.*;

/**
 * Created by ever on 2016/10/9.
 */
@Controller
@RequestMapping(value = "/admin/tree")
public class TreeAction {
    @Autowired
    private LandMassDao landMassDao;
    @Autowired
    TreeDao treeDao;
    @Autowired
    OutboundOrderDao outboundOrderDao;
    @Autowired
    private StorageService storageService;
    @Autowired
    private PushService pushService;
    @Autowired
    private TreeService treeService;
    @Autowired
    private CostService costService;
    @Value("${ip}")
    String ip;

    @RequestMapping("/seek")
    public String list(Model model) {
        return "admin/tree/tree_list";
    }

    @RequestMapping("/out")
    public String out(Model model) {
        List<OutboundOrder> outStatus = outboundOrderDao.findByStatus(1);
        List<Tree> treeList=new ArrayList<>();
        for(OutboundOrder out:outStatus){
            if(Objects.nonNull(out.getTrees())&&out.getTrees().size()>0){
                Tree tree = out.getTrees().get(0);
                tree.setTree_id(out.getOutboundOrder_id());
                if(Objects.nonNull(out.getLandMass_id())){
                    LandMass landMass=landMassDao.findOne(out.getLandMass_id());
                    if(Objects.nonNull(landMass)){
                        tree.setSerialNumber(landMass.getAreaLocation().getSerialNumber()+landMass.getSerialNumber());
                    }else {
                        tree.setSerialNumber("");
                    }
                }else {
                    tree.setSerialNumber("");
                }
                tree.setNumber(Integer.parseInt(out.getQuantity()+""));
                if(Objects.nonNull(out.getTransactionAmount())){
                    tree.setPrice(out.getTransactionAmount().doubleValue());
                }else {
                    tree.setPrice(0);
                }
                tree.setUsername(out.getName());
                treeList.add(tree);
            }
            Collections.sort(treeList, new Comparator<Tree>() {
                @Override
                public int compare(Tree o1, Tree o2) {
                   return o2.getOutWarehouseTime().compareTo(o1.getOutWarehouseTime());
                }
            });
        }
        model.addAttribute("trees",treeList);
        return "admin/tree/out_list";
    }

    @RequestMapping("/put")
    public String put(Model model) {
        List<Tree> trees=new ArrayList<>();
        for (Tree tree:treeDao.findPutWarehouse()) {
            LandMass landMass= landMassDao.findOne(tree.getLandmassid());
            if(Objects.nonNull(landMass)){
                tree.setPlace(landMass.getAreaLocation().getSerialNumber()+landMass.getSerialNumber());
            }
            trees.add(tree);
        }
        model.addAttribute("trees",trees);
        return "admin/tree/put_list";
    }

    @RequestMapping("/payment")
    public String payment(Long tree_id) {
        if(Objects.nonNull(tree_id)){
            Tree tree=treeDao.findOne(tree_id);
            treeDao.updatePayment(true,tree.getSerialNumber());
        }
        return "redirect:/admin/tree/put";
    }

    @RequestMapping("/gather")
    public String gather(Long tree_id) {
        if(Objects.nonNull(tree_id)){
            treeService.gather(tree_id);
        }
        return "redirect:/admin/tree/out";
    }

    @RequestMapping("/direction")
    public String direction(String direction,Model model){
        List<Tree> trees=new ArrayList<>();
        if(!("".equals(direction))){
           for (Tree tree:treeDao.findPutWarehouse()) {
                if(direction.equals(tree.getDirection())){
                    trees.add(tree);
                }
           }
       }
       model.addAttribute("trees",trees);
        return "admin/tree/direction_list";
    }

    @RequestMapping("/treeWell")
    @ResponseBody
    public List<TreeWell> treeWell(Long id){
        List<TreeWell> treeWells=new ArrayList<>();
        LandMass landMass=landMassDao.findOne(id);
        if(Objects.nonNull(landMass)){
            treeWells=landMass.getTreeWells();
        }
        return treeWells;
    }


    @PostMapping("/outtree")
    @ResponseBody
    public String out(String treeids){
        Subject currentUser = SecurityUtils.getSubject();
        String username = currentUser.getSession().getAttribute("username").toString();
        int out = storageService.out(treeids, username);
        pushService.inform("finance","有"+out+"棵苗木需要出库审核");
        return "出库"+out+"棵";
    }

    @PostMapping("/marktree")
    @ResponseBody
    public String mark(String treeids ,String remark,int look){
        Subject currentUser = SecurityUtils.getSubject();
        String name = currentUser.getSession().getAttribute("username").toString();
        int out = storageService.mark(treeids, name, new Date(),remark,look);
        return "号苗"+out+"棵";
    }


    @PostMapping("/dietree")
    @ResponseBody
    public String die(String treeids){
        Subject currentUser = SecurityUtils.getSubject();
        String name = currentUser.getSession().getAttribute("username").toString();
        int out = storageService.die(treeids,name);
        pushService.inform("finance","有"+out+"棵苗木死亡需要确认");
        return "标记死苗"+out+"棵";
    }

    @PostMapping("/updatetree")
    public String updatetree(String landMass_id,String treeids, double chestBreadth,double chestBreadthmax,
                             double crownWidth ,double crownWidthmax , double height,double heightmax,
                             String salenumber,String salenumbermax,String remark, MultipartFile file,double cost){
        Subject currentUser = SecurityUtils.getSubject();
        String name = currentUser.getSession().getAttribute("username").toString();
        String imgurl= FileUtil.savefile(file);
        storageService.updateinfo(treeids,chestBreadth,chestBreadthmax, crownWidth,crownWidthmax ,height,heightmax,
                (salenumber!=null&&salenumber.length()>0?(new Double(salenumber).intValue()):0),
                (salenumbermax!=null&&salenumbermax.length()>0?(new Double(salenumbermax).intValue()):0),
                remark, imgurl,name,cost);
        return "redirect:/admin/landMass/treeWell?landMass_id="+landMass_id;
    }

    @RequestMapping("/getimg")
    @ResponseBody
    public Tree getimg(Long treeid){
        Tree tree=new Tree();
        String img="";
        String addres="";
        addres = "http://" + ip + ":8090/";
        double costing = costService.costing();
        BigDecimal b=new BigDecimal(costing);
        double b2=b.setScale(2,BigDecimal.ROUND_UP).doubleValue();
        Tree trees=treeDao.findOne(treeid);
        if(Objects.nonNull(trees)){
            img=addres +trees.getImgurl();
            tree=trees;
            tree.setImgurl(img);
            tree.setCost(b2);
        }
        return tree;
    }
}
